package controller.ur;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.AlbumDaoLocal;
import model.dao.PhotoDaoLocal;
import model.entity.Album;
import model.entity.Photo;
import model.entity.User;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import controller.CUtil;

/**
 * Servlet implementation class SUploadPhotoOut
 */
public class SUploadPhotoOut extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	private Logger log=Logger.getLogger(SUploadPhotoOut.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SUploadPhotoOut() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		request.setCharacterEncoding("UTF-8");
		
		if (ServletFileUpload.isMultipartContent(request)) {
			List<FileItem> items = null;
			Photo photo=null;
			BufferedImage img = null;
			String imageFilePath=null;
			String imageFilePathThumb=null;
			int size=0;
			
			String title=null;
			String description=null;
			Boolean ispublic=false;
			Boolean tagsAllowed=false;
			Boolean notesAllowed=false;
			Boolean commentsAllowed=false;
			Integer albumId=null;
			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(3000000);
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(3000000);
				items =upload.parseRequest(request);
				for (FileItem f : items) {
					if (f.isFormField()) {
						String name = f.getFieldName();
						String value = f.getString("UTF-8");
						if (name.equals("title")) {
							title=value;
						}else if (name.equals("description")) {
							description=value;
						}else if (name.equals("album")) {
							albumId=Integer.parseInt(value);
						}else if (name.equals("ispublic")) {
							ispublic=true;
						}else if (name.equals("tagsallowed")) {
							tagsAllowed=true;
						}else if (name.equals("notesallowed")) {
							notesAllowed=true;
						}else if (name.equals("commentsallowed")) {
							commentsAllowed=true;
						}
					}else{
						photo=new Photo();
						photoDao.persist(photo);
						String extension = (f.getName().split("\\."))[1];
						imageFilePath = "\\images\\photo" + photo.getId() + "."
								+ extension;
						imageFilePathThumb = "\\images\\tphoto" + photo.getId() + "."
								+ extension;
						
						File uploadedFile = new File(getServletContext().getRealPath("")+imageFilePath);
						try {
							f.write(uploadedFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
						try {
							String sc=getServletContext().getRealPath("");
						    img = ImageIO.read(new File(sc+imageFilePath));
						    saveScaledImage(sc+imageFilePath,sc+imageFilePathThumb);
						} catch (IOException e) {
						}
						size=(int)f.getSize();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

			photo.setHeight(img.getHeight());
			photo.setWidth(img.getWidth());
			photo.setLocation(imageFilePath);
			photo.setThumbnailLocation(imageFilePathThumb);
			photo.setSize(size);
			photo.setUploadDate(new Date());
			photo.setTitle(title);
			photo.setDescription(description);
			photo.setPub(ispublic);
			photo.setTagsAllowed(tagsAllowed);
			photo.setCommentsAllowed(commentsAllowed);
			photo.setNotesAllowed(notesAllowed);
			photo.setRating(0d);
			Album album=albumDao.findById(albumId);
			album.getPhotos().add(photo);
			photo.getAlbums().add(album);
			albumDao.merge(album);
			photoDao.merge(photo);
			
			if(photo.getPub()){
				User user=(User)request.getSession().getAttribute("user");
				String messageTitle="New photo from: "+user.getFirstName()+" "+user.getLastName();
				String messageText=messageTitle+". Photo title: "+photo.getTitle();
				for(User u:user.getFollowers()){
					if(u.getEmailNotifications()){
						CUtil.sendMail(messageTitle, messageText, u.getEmail());
					}
				}
			}
			log.info("Photo uploaded: "+photo.toString());
			CUtil.lastPageRedirect(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private  void saveScaledImage(String filePath,String outputFile){
	    try {

	        BufferedImage sourceImage = ImageIO.read(new File(filePath));
	        int width = sourceImage.getWidth();
	        int height = sourceImage.getHeight();

	        if(width>height){
	            float extraSize=    height-100;
	            float percentHight = (extraSize/height)*100;
	            float percentWidth = width - ((width/100)*percentHight);
	            BufferedImage img = new BufferedImage((int)percentWidth, 100, BufferedImage.TYPE_INT_RGB);
	            Image scaledImage = sourceImage.getScaledInstance((int)percentWidth, 100, Image.SCALE_SMOOTH);
	            img.createGraphics().drawImage(scaledImage, 0, 0, null);
	            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
	            img2 = img.getSubimage((int)((percentWidth-100)/2), 0, 100, 100);

	            ImageIO.write(img2, "jpg", new File(outputFile));    
	        }else{
	            float extraSize=    width-100;
	            float percentWidth = (extraSize/width)*100;
	            float  percentHight = height - ((height/100)*percentWidth);
	            BufferedImage img = new BufferedImage(100, (int)percentHight, BufferedImage.TYPE_INT_RGB);
	            Image scaledImage = sourceImage.getScaledInstance(100,(int)percentHight, Image.SCALE_SMOOTH);
	            img.createGraphics().drawImage(scaledImage, 0, 0, null);
	            BufferedImage img2 = new BufferedImage(100, 100 ,BufferedImage.TYPE_INT_RGB);
	            img2 = img.getSubimage(0, (int)((percentHight-100)/2), 100, 100);

	            ImageIO.write(img2, "jpg", new File(outputFile));
	        }

	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
	    }
	}
}
